package cn.com.ddapp.ddm.fragment.base.mine;

import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.ypy.eventbus.EventBus;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;
import cn.com.ddapp.ddm.AppConfig;
import cn.com.ddapp.ddm.R;
import cn.com.ddapp.ddm.adapter.CouponsAdapter;
import cn.com.ddapp.ddm.api.OKUtilAPI;
import cn.com.ddapp.ddm.base.BaseApplication;
import cn.com.ddapp.ddm.bean.Coupons;
import cn.com.ddapp.ddm.bean.CouponsEntity;
import cn.com.ddapp.ddm.bean.mine.MyEvent;
import cn.com.ddapp.ddm.fragment.base.BaseFragment;
import cn.com.ddapp.ddm.inter.OkUtilCallback;
import cn.com.ddapp.ddm.ui.empty.EmptyLayout;
import cn.com.ddapp.ddm.util.SPUtils;
import cn.com.ddapp.ddm.util.TLog;
import cn.com.ddapp.ddm.widget.pulltorefresh.PullToRefreshLayout;
import cn.com.ddapp.ddm.widget.pulltorefresh.pullableview.PullableListView;

/**
 * Created by admin on 2016/8/16.
 */
public class CouponsListFragment extends BaseFragment implements View.OnClickListener {

    @BindView(R.id.pullToRefreshLayout)
    PullToRefreshLayout pullToRefreshLayout;
    @BindView(R.id.listview_coupons)
    PullableListView pullableListView;
    @BindView(R.id.error_layout)
    EmptyLayout mEmptyLayout;
    @BindView(R.id.collectionCheckBox)
    CheckBox checkBox;
    @BindView(R.id.noL)
    AutoRelativeLayout noConpons;
    @BindView(R.id.bottom_delete)
    AutoLinearLayout bottom_delete;
    @BindView(R.id.delete_btn)
    TextView deleteBtn;
    @BindView(R.id.cancle_btn)
    TextView cancleBtn;


    private Integer st = 0;//数据起始
    private CouponsAdapter couponsAdapter;
    private Coupons coupons;
    private Integer type = 0;
    String userId;
    int id1;

    private List<Coupons> couponsList = new ArrayList<Coupons>();


    public static CouponsListFragment newInstance(int type) {
        Bundle bundle = new Bundle();
        bundle.putInt("type", type);
        CouponsListFragment fragment = new CouponsListFragment();
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    protected String getFragmentTag() {
        return null;
    }

    @Override
    protected void initData() {
        EventBus.getDefault().register(this);
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        type = (Integer) this.getArguments().get("type");
        coupons = new Coupons();
        userId = SPUtils.getStringData(getActivity(), SPUtils.USERID);
        st = 0;
        requestData(st);
        mEmptyLayout.setOnClickListener(this);
        pullToRefreshLayout.setOnRefreshListener(new PullToRefreshLayout.OnRefreshListener() {

            @Override
            public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
                st = 0;
                requestData(st);
            }

            @Override
            public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
                requestMoreData(st);
            }
        });

        if (type != 0){
            //设置长按监听
            pullableListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                    couponsAdapter.setEditable(true);
                    bottom_delete.setVisibility(View.VISIBLE);
                    return false;
                }
            });
        }

        pullableListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                //切换某一个列表项的选中状态
                couponsAdapter.toggleItemCheckedState(i);
                couponsAdapter.notifyDataSetChanged();
            }
        });
    }


    private void requestData(final int s) {
        mEmptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
        final OkUtilCallback okUtilCallback = new OkUtilCallback(mEmptyLayout) {
            @Override
            public void onMyResponse(String response, int id) {
                TLog.log(response);
                CouponsEntity entity = gson.fromJson(response, CouponsEntity.class);
                if ((!AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult())) && entity.getLogin()) {
                    mEmptyLayout.setErrorType(EmptyLayout.NO_LOGIN);
                } else if ((!AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))) {
                    BaseApplication.getIntstance().showToast(entity.getResult(), Toast.LENGTH_SHORT, 0, Gravity.CENTER);
                } else if (entity.getList().size() == 0) {
                    noConpons.setVisibility(View.VISIBLE);
                } else {
                    couponsList = entity.getList();
                    st = s + couponsList.size();
                    couponsAdapter = new CouponsAdapter(couponsList, getActivity(), type);
                    couponsAdapter.notifyDataSetChanged();
                    pullableListView.setAdapter(couponsAdapter);
                    pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
                }
            }
        };
        /* userId  int[Y]
           type  int[Y] 0:未使用  1:已使用 2:已过期
           st int[N]  开始读取的行，默认从0开始读取 */
        OKUtilAPI.post(OKUtilAPI.getCoupons, "userId=" + userId + "&type=" + type + "&st=" + st, okUtilCallback);
    }

    private void requestMoreData(final int s) {
        mEmptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
        final OkUtilCallback okUtilCallback = new OkUtilCallback(mEmptyLayout) {
            @Override
            public void onMyResponse(String response, int id) {
                TLog.log(response);
                CouponsEntity entity = gson.fromJson(response, CouponsEntity.class);
                if ((!AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))) {
                    BaseApplication.getIntstance().showToast(entity.getResult(), Toast.LENGTH_SHORT, 0, Gravity.CENTER);
                } else{
                    List<Coupons> ll=entity.getList();
                    if (ll.size() > 0) {
                        couponsList.addAll(ll);
                        st = s + ll.size();
                        couponsAdapter.notifyDataSetChanged();
                        pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
                    } else {
                        pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.NODATA);
                    }
                }
            }
        };
        /*userId  int[Y]
        type  int[Y] 0:未使用  1:已使用 2:已过期
        st int[N]  开始读取的行，默认从0开始读取*/
        OKUtilAPI.post(OKUtilAPI.getCoupons, "userId=" + userId + "&type=" + type + "&st=" + st, okUtilCallback);
    }


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_coupons;
    }

    @Override
    public void onClick(View view) {

    }
    @OnClick({R.id.collectionCheckBox,R.id.delete_btn,R.id.cancle_btn})
    public void onclick(View view){
        switch (view.getId()){
            case R.id.collectionCheckBox :
                if (checkBox.isChecked()){
                    couponsAdapter.setAllItemChecked(true);
                }else {
                    couponsAdapter.setAllItemChecked(false);
                }
                break;
            case R.id.cancle_btn :
                couponsAdapter.setEditable(false);
                bottom_delete.setVisibility(View.GONE);
                break;
            case R.id.delete_btn :
                //获取当前列表中所有已勾选的实体数据
                ArrayList<Coupons> checkedDatas = couponsAdapter.getCheckedDatas();
                OkUtilCallback callback = new OkUtilCallback() {
                    @Override
                    public void onMyResponse(String response, int id) {
                        Gson gson = new Gson();
                        CouponsEntity coup = gson.fromJson(response, CouponsEntity.class);
                        if ((!AppConfig.RESULT_OK.equalsIgnoreCase(coup.getResult())) && coup.getLogin()) {
                            mEmptyLayout.setErrorType(EmptyLayout.NO_LOGIN);
                        } else if ((!AppConfig.RESULT_OK.equalsIgnoreCase(coup.getResult()))) {
                            BaseApplication.getIntstance().showToast(coup.getResult(), Toast.LENGTH_SHORT, 0, Gravity.CENTER);
                        }else if((AppConfig.RESULT_OK.equalsIgnoreCase(coup.getResult()))){
                            for (int j = 0;j<couponsList.size();j++){
                                if (couponsList.get(j).getId() == id1){
                                    couponsList.remove(j);
                                    couponsAdapter.notifyDataSetChanged();
                                }
                            }
                            couponsAdapter.setEditable(false);
                            bottom_delete.setVisibility(View.GONE);
                            if (couponsList.size()==0){
                                noConpons.setVisibility(View.VISIBLE);
                            }
                        }
                    }
                };
                for (int i=0; i<checkedDatas.size();i++){
                    /*userId [Y] 会员ID
                    id [Y] 优惠券ID*/
                    id1 = checkedDatas.get(i).getId();
                    OKUtilAPI.post(OKUtilAPI.delCoupons,"userId="+userId+"&id="+id1,callback);
                }
                break;
        }
    }

    public void onEventMainThread(MyEvent e) {
        if (couponsAdapter!=null){
            couponsAdapter.setEditable(false);
        }
        bottom_delete.setVisibility(View.GONE);
        st = 0;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
